import { NextRequest, NextResponse } from 'next/server';
import { PrismaService } from '@/services/database/PrismaService';

const prismaService = new PrismaService();

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const chain = searchParams.get('chain');
    const address = searchParams.get('address');
    const limit = parseInt(searchParams.get('limit') || '50');

    const page = parseInt(searchParams.get('page') || '1');
    const pageSize = limit;
    const skip = (page - 1) * pageSize;

    let transactions;
    let total = 0;
    
    if (address && chain) {
      transactions = await prismaService.getTransactionsByAddress(address, chain as any);
      total = transactions.length;
    } else {
      // Get recent transactions with proper pagination
      const prisma = prismaService.getClient();
      
      // Get total count first
      const whereClause = chain ? { chain } : {};
      total = await prisma.transaction.count({ where: whereClause });
      
      // Get paginated transactions
      transactions = await prisma.transaction.findMany({
        take: pageSize,
        skip: skip,
        orderBy: { timestamp: 'desc' },
        where: whereClause
      });
    }

    // 转换BigInt字段为字符串以避免序列化错误，并修正字段名
    const serializedTransactions = transactions.map(tx => ({
      ...tx,
      id: tx.id.toString(),
      from: tx.fromAddress,
      to: tx.toAddress,
      valueUSD: Number(tx.valueUsd),
      blockNumber: tx.blockNumber?.toString(),
      gasUsed: tx.gasUsed?.toString(),
      gasPrice: tx.gasPrice?.toString(),
      confirmed: tx.confirmed !== undefined ? tx.confirmed : true
    }));

    const totalPages = Math.ceil(total / pageSize);

    return NextResponse.json({
      success: true,
      data: {
        items: serializedTransactions,
        page: page,
        limit: pageSize,
        total: total,
        totalPages: totalPages,
        hasMore: page < totalPages
      },
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    console.error('Failed to fetch transactions:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: error instanceof Error ? error.message : 'Failed to fetch transactions',
        timestamp: new Date().toISOString()
      },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const transaction = await request.json();
    
    await prismaService.saveTransaction(transaction);
    
    return NextResponse.json({
      success: true,
      message: 'Transaction saved successfully',
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    console.error('Failed to save transaction:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: error instanceof Error ? error.message : 'Failed to save transaction',
        timestamp: new Date().toISOString()
      },
      { status: 500 }
    );
  }
} 